<script setup lang='ts'>

import { getBirdsListService, updateBirdInfoService, deleteBirdInfoService, addBirdInfoService } from '@/api/birds'
import type { FormInstance, FormRules } from 'element-plus'
import { uploadFileService } from '@/api/other'
import { genFileId } from 'element-plus'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import { useTokenStore } from '@/stores/token'

const tokenStore = useTokenStore()

interface RuleForm {
    id: string,
    morphologyAndFeatures: string,
    name: string,
    habits: string,
    species: string,
    imageUrl: string,
    soundUrl: string,
    description: string,
    growthAndDistribution: string,
    createdAt: string,
    updatedAt: string
}

//控制用户详细，编辑，删除弹窗
const dialogVisible = ref(false)

//控制删除确认弹窗
const deleteDialogVisible = ref(false)

//控制弹窗标题
const dialogTitle = ref('')

//控制弹窗input能否输入
const inputDisabled = ref(true)

//控制最后确定按钮是否可用
const submitDisabled = ref(true)

//定义模型，用于鸟类信息详细展示，以及中转copy
const birdInfoModel = ref({
    id: 0,
    morphologyAndFeatures: '',
    name: '',
    habits: '',
    species: '',
    imageUrl: '',
    soundUrl: '',
    description: '',
    growthAndDistribution: '',
    createdAt: '',
    updatedAt: ''
})

//定义模型，用于鸟类信息修改
const birdInfoChangeModel = ref({
    id: 0,
    morphologyAndFeatures: '',
    name: '',
    habits: '',
    species: '',
    imageUrl: '',
    soundUrl: '',
    description: '',
    growthAndDistribution: '',
    // createdAt: '',
    // updatedAt: ''
})

//定义模型，用于添加鸟类信息
const birdInfoAddModel = ref({
    morphologyAndFeatures: '',
    name: '',
    habits: '',
    species: '',
    imageUrl: '',
    soundUrl: '',
    description: '',
    growthAndDistribution: '',
})

//设置表单校验规则
const rules = reactive<FormRules<RuleForm>>({
    // nickname: [
    //     { required: true, message: 'Please input nickname', trigger: 'blur' },
    //     { min: 1, max: 8, message: 'Length should be 1 to 8', trigger: 'blur' },
    // ],
    // introduction: [
    //     { max: 50, message: '长度必须小于50', trigger: 'blur' }
    // ]
})

const handleClick = () => {
    console.log('click')
}

const tableData = ref([
    {
        id: '2016-05-03',
        morphologyAndFeatures: 'Tom',
        name: 'California',
        habits: 'Los Angeles',
        species: 'No. 189, Grove St, Los Angeles',
        imageUrl: 'CA 90036',
        soundUrl: 'Home',
        description: 'No. 189, Grove St, Los Angeles',
        growthAndDistribution: '1',
        createdAt: '1',
        updatedAt: '1'
    }
])

// 定义 speciesFields，用于分开的输入字段
const speciesFields = ref({
    class: '',
    genus: '',
    order: '',
    family: '',
    species: ''
})

//调用后台接口获取鸟类信息列表
const getBirdsList = async () => {

    let result = await getBirdsListService()
    console.log("鸟类信息列表" + result)
    tableData.value = result.data

}
getBirdsList()

//调用后台接口更新鸟类信息
const updateBirdInfo = async () => {

    //数据拷贝从birdInfoModel拷贝到birdInfoChangeModel
    birdInfoChangeModel.value.id = birdInfoModel.value.id;
    birdInfoChangeModel.value.morphologyAndFeatures = birdInfoModel.value.morphologyAndFeatures;
    birdInfoChangeModel.value.name = birdInfoModel.value.name;
    birdInfoChangeModel.value.habits = birdInfoModel.value.habits;
    birdInfoChangeModel.value.species = birdInfoModel.value.species;
    birdInfoChangeModel.value.imageUrl = birdInfoModel.value.imageUrl;
    birdInfoChangeModel.value.soundUrl = birdInfoModel.value.soundUrl;
    birdInfoChangeModel.value.growthAndDistribution = birdInfoModel.value.growthAndDistribution;
    birdInfoChangeModel.value.description = birdInfoModel.value.description;
    // birdInfoChangeModel.value.createdAt = birdInfoModel.value.createdAt;
    // birdInfoChangeModel.value.updatedAt = birdInfoModel.value.updatedAt;

    console.log("更新鸟类信息birdInfoChangeModel：" + birdInfoChangeModel.value.id)
    let result = await updateBirdInfoService(birdInfoChangeModel.value)
    console.log("更新鸟类信息result：" + result)
    dialogVisible.value = false;
    getBirdsList();

}

//调用后台接口删除鸟类信息
const deleteUserInfo = async () => {

    let result = await deleteBirdInfoService(birdInfoModel.value.id)
    console.log("删除鸟类信息result：" + result)
    dialogVisible.value = false;
    deleteDialogVisible.value = false;
    getBirdsList();

}

//调用后台接口添加鸟类信息
const addBirdInfo = async () => {

    let result = await addBirdInfoService(birdInfoAddModel.value)
    console.log("添加鸟类信息result：" + result)
    dialogVisible.value = false;
    getBirdsList();

}

//调用后台接口上传文件
const uploadFile = async (file) => {

    let result = await uploadFileService(file)
    console.log("上传文件result：" + result)


}

//数据拷贝到birdInfoModel
//由于多处需要用到数据拷贝，所以写一个函数
const copyData = (row) => {
    //数据拷贝
    birdInfoModel.value.id = row.id
    birdInfoModel.value.name = row.name
    birdInfoModel.value.morphologyAndFeatures = row.morphologyAndFeatures
    birdInfoModel.value.habits = row.habits
    birdInfoModel.value.species = row.species
    birdInfoModel.value.imageUrl = row.imageUrl
    birdInfoModel.value.soundUrl = row.soundUrl
    birdInfoModel.value.growthAndDistribution = row.growthAndDistribution
    birdInfoModel.value.description = row.description
    birdInfoModel.value.createdAt = row.createdAt
    birdInfoModel.value.updatedAt = row.updatedAt
}

//展示鸟类信息详细弹窗
const showDetailDialog = (row) => {

    dialogVisible.value = true;
    dialogTitle.value = '鸟类信息';
    inputDisabled.value = true;
    submitDisabled.value = true;

    //数据拷贝
    copyData(row)

     // 将 birdInfoModel.species 解析为 speciesFields
     if (birdInfoModel.value.species) {
        speciesFields.value = JSON.parse(birdInfoModel.value.species)
    }

}

//展示编辑鸟类信息弹窗
const showEditDialog = (row) => {

    dialogVisible.value = true;
    dialogTitle.value = '编辑信息';
    inputDisabled.value = false;
    submitDisabled.value = false;

    //数据拷贝
    copyData(row)

     // 将 birdInfoModel.species 解析为 speciesFields
     if (birdInfoModel.value.species) {
        speciesFields.value = JSON.parse(birdInfoModel.value.species)
    }

}

//展示删除鸟类信息弹窗
const showDeleteDialog = (row) => {

    dialogVisible.value = true;
    dialogTitle.value = '删除鸟类';
    inputDisabled.value = true;
    submitDisabled.value = false;

    //数据拷贝
    copyData(row)

     // 将 birdInfoModel.species 解析为 speciesFields
     if (birdInfoModel.value.species) {
        speciesFields.value = JSON.parse(birdInfoModel.value.species)
    }

}

//展示添加鸟类信息弹窗
const showAddDialog = () => {

    dialogVisible.value = true;
    dialogTitle.value = '添加鸟类';
    inputDisabled.value = false;
    submitDisabled.value = false;

    //清空数据
    birdInfoModel.value.id = 0;
    birdInfoModel.value.morphologyAndFeatures = '';
    birdInfoModel.value.name = '';
    birdInfoModel.value.habits = '';
    birdInfoModel.value.species = '';
    birdInfoModel.value.imageUrl = '';
    birdInfoModel.value.soundUrl = '';
    birdInfoModel.value.growthAndDistribution = '';
    birdInfoModel.value.description = '';
    birdInfoModel.value.createdAt = '';
    birdInfoModel.value.updatedAt = '';

    // 重置 speciesFields
    speciesFields.value = {
        class: '',
        genus: '',
        order: '',
        family: '',
        species: ''
    }

}

//因为确定又分为编辑用户和删除用户，所调用的函数不同，所以写一个提交函数来做判断
const submit = () => {

    if (dialogTitle.value == '编辑信息') {
        // 合并 speciesFields 为 JSON 对象，并赋值给 birdInfoModel.species
        birdInfoModel.value.species = JSON.stringify(speciesFields.value)
        updateBirdInfo();
    } else if (dialogTitle.value == '删除鸟类') {
        //弹出删除确认弹窗
        deleteDialogVisible.value = true;
    } else if (dialogTitle.value == '添加鸟类') {
        // 合并 speciesFields 为 JSON 对象，并赋值给 birdInfoModel.species
        birdInfoModel.value.species = JSON.stringify(speciesFields.value)

        //将添加的birdInfoModel数据拷贝到birdInfoAddModel
        // birdInfoAddModel.value.id = birdInfoModel.value.id;
        birdInfoAddModel.value.morphologyAndFeatures = birdInfoModel.value.morphologyAndFeatures;
        birdInfoAddModel.value.name = birdInfoModel.value.name;
        birdInfoAddModel.value.habits = birdInfoModel.value.habits;
        birdInfoAddModel.value.species = birdInfoModel.value.species;
        birdInfoAddModel.value.description = birdInfoModel.value.description;
        birdInfoAddModel.value.growthAndDistribution = birdInfoModel.value.growthAndDistribution;
        birdInfoAddModel.value.imageUrl = birdInfoModel.value.imageUrl;
        birdInfoAddModel.value.soundUrl = birdInfoModel.value.soundUrl;

        addBirdInfo();

    }

}

//上传图片(从element-plus复制的部分)
const uploadImg = ref<UploadInstance>()

const handleExceedImg: UploadProps['onExceed'] = (files) => {
    uploadImg.value!.clearFiles()
    const file = files[0] as UploadRawFile
    file.uid = genFileId()
    uploadImg.value!.handleStart(file)
}

const submitUploadImg = () => {
    uploadImg.value!.submit()
}

//图片上传成功之后的回调
const handleUploadImgSuccess = (response, file) => {
    // 从响应中获取上传成功后的文件 URL
    const imageUrl = response.data; // 假设响应中包含一个名为 url 的字段

    // console.log("上传成功后的文件URL：" + imageUrl)

    //存储到对象里
    birdInfoModel.value.imageUrl = imageUrl;

}

//上传音频(从element-plus复制的部分)
const uploadSound = ref<UploadInstance>()

const handleExceedSound: UploadProps['onExceed'] = (files) => {
    uploadSound.value!.clearFiles()
    const file = files[0] as UploadRawFile
    file.uid = genFileId()
    uploadSound.value!.handleStart(file)
}

const submitUploadSound = () => {
    uploadSound.value!.submit()
}

//音频上传成功之后的回调
const handleUploadSoundSuccess = (response, file) => {
    // 从响应中获取上传成功后的文件 URL
    const soundUrl = response.data; // 假设响应中包含一个名为 url 的字段

    // console.log("上传成功后的文件URL：" + imageUrl)

    //存储到对象里
    birdInfoModel.value.soundUrl = soundUrl;

}

</script>

<template>
    <div class="container">
        <el-button type="primary" @click="showAddDialog()">添加鸟类</el-button>
        <el-table :data="tableData" style="width: 100%">
            <el-table-column fixed prop="name" label="Name" width="150" />
            <el-table-column prop="id" label="Id" width="120" />
            <!-- <el-table-column prop="morphologyAndFeatures" label="MorphologyAndFeatures" width="120" /> -->
            <!-- <el-table-column prop="habits" label="Habits" width="120" /> -->
            <!-- <el-table-column prop="imageUrl" label="ImageUrl" width="120" /> -->
            <!-- <el-table-column prop="soundUrl" label="SoundUrl" width="120" /> -->
            <!-- <el-table-column prop="description" label="Description" width="120" /> -->
            <!-- <el-table-column prop="growthAndDistribution" label="GrowthAndDistribution" width="120" /> -->
            <el-table-column prop="createdAt" label="CreatedAt" width="120" />
            <el-table-column prop="updatedAt" label="UpdatedAt" width="120" />
            <el-table-column fixed="right" label="Operations" width="180">
                <template #default="{ row }">
                    <el-button link type="primary" size="small" @click="showDetailDialog(row)">详细</el-button>
                    <el-button link type="primary" size="small" @click="showEditDialog(row)">编辑</el-button>
                    <el-button link type="primary" size="small" @click="showDeleteDialog(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 详细，编辑，删除,添加弹窗 -->
        <el-dialog :title="dialogTitle" v-model="dialogVisible" width="70%">
            <el-form :model="birdInfoModel" :rules="rules">
                <el-form-item label="Name" prop="name">
                    <el-input v-model="birdInfoModel.name" placeholder="birdInfoModel.name" :disabled="inputDisabled" />
                </el-form-item>
                <el-form-item label="Id" prop="id">
                    <el-input v-model="birdInfoModel.id" placeholder="birdInfoModel.id" disabled />
                </el-form-item>
                <el-form-item label="CreatedAt" prop="createdAt">
                    <el-input v-model="birdInfoModel.createdAt" placeholder="birdInfoModel.createdAt" disabled />
                </el-form-item>
                <el-form-item label="UpdatedAt" prop="updatedAt">
                    <el-input v-model="birdInfoModel.updatedAt" placeholder="birdInfoModel.updatedAt" disabled />
                </el-form-item>
                <el-form-item label="MorphologyAndFeatures" prop="morphologyAndFeatures">
                    <el-input type="textarea" v-model="birdInfoModel.morphologyAndFeatures"
                        placeholder="birdInfoModel.morphologyAndFeatures" :disabled="inputDisabled" />
                </el-form-item>
                <el-form-item label="Habits" prop="habits">
                    <el-input type="textarea" v-model="birdInfoModel.habits" placeholder="birdInfoModel.habits"
                        :disabled="inputDisabled" />
                </el-form-item>

                
                <!-- <el-form-item label="Species" prop="species">
                    <el-input type="textarea" v-model="birdInfoModel.species" placeholder="birdInfoModel.species"
                        :disabled="inputDisabled" />
                </el-form-item> -->
                <el-form-item label="Class(纲)" prop="class">
                    <el-input v-model="speciesFields.class" placeholder="Class" :disabled="inputDisabled" />
                </el-form-item>
                <el-form-item label="Genus(属)" prop="genus">
                    <el-input v-model="speciesFields.genus" placeholder="Genus" :disabled="inputDisabled" />
                </el-form-item>
                <el-form-item label="Order(目)" prop="order">
                    <el-input v-model="speciesFields.order" placeholder="Order" :disabled="inputDisabled" />
                </el-form-item>
                <el-form-item label="Family(科)" prop="family">
                    <el-input v-model="speciesFields.family" placeholder="Family" :disabled="inputDisabled" />
                </el-form-item>
                <el-form-item label="Species(种)" prop="species">
                    <el-input v-model="speciesFields.species" placeholder="Species" :disabled="inputDisabled" />
                </el-form-item>

                <el-form-item label="ImageUrl" prop="imageUrl">
                    <el-input type="textarea" v-model="birdInfoModel.imageUrl" placeholder="birdInfoModel.imageUrl"
                        :disabled="inputDisabled" />
                    <!-- <el-button class="btn-uploadImg" type="primary">上传图片</el-button> -->
                    <el-upload ref="uploadImg" class="upload-img" action="/api/upload" :limit="1"
                        :headers="{ 'token': tokenStore.token }" :on-exceed="handleExceedImg" :auto-upload="false"
                        :on-success="handleUploadImgSuccess">
                        <template #trigger>
                            <el-button type="primary" :disabled="inputDisabled">选择图片</el-button>
                        </template>
                        <!-- 添加一个空白的span元素让两个按钮之间有间距 -->
                        <span style="margin-left: 10px;"></span>
                        <el-button class="ml-3" type="success" @click="submitUploadImg" :disabled="inputDisabled">
                            上传图片
                        </el-button>
                        <template #tip>
                            <div class="el-upload__tip text-red">
                                文件大小不超过1048576 bytes
                            </div>
                        </template>
                    </el-upload>
                </el-form-item>
                <el-form-item label="SoundUrl" prop="soundUrl">
                    <el-input type="textarea" v-model="birdInfoModel.soundUrl" placeholder="birdInfoModel.soundUrl"
                        :disabled="inputDisabled" />
                    <!-- <el-button class="btn-uploadSound" type="primary">上传音频</el-button> -->
                    <el-upload ref="uploadSound" class="upload-sound" action="/api/upload" :limit="1"
                        :headers="{ 'token': tokenStore.token }" :on-exceed="handleExceedSound" :auto-upload="false"
                        :on-success="handleUploadSoundSuccess">
                        <template #trigger>
                            <el-button type="primary" :disabled="inputDisabled">选择音频</el-button>
                        </template>
                        <!-- 添加一个空白的span元素让两个按钮之间有间距 -->
                        <span style="margin-left: 10px;"></span>
                        <el-button class="ml-3" type="success" @click="submitUploadSound" :disabled="inputDisabled">
                            上传音频
                        </el-button>
                        <template #tip>
                            <div class="el-upload__tip text-red">
                                文件大小不超过1048576 bytes
                            </div>
                        </template>
                    </el-upload>
                </el-form-item>
                <el-form-item label="Description" prop="description">
                    <el-input type="textarea" v-model="birdInfoModel.description"
                        placeholder="birdInfoModel.description" :disabled="inputDisabled" />
                </el-form-item>
                <el-form-item label="GrowthAndDistribution" prop="growthAndDistribution">
                    <el-input type="textarea" v-model="birdInfoModel.growthAndDistribution"
                        placeholder="birdInfoModel.growthAndDistribution" :disabled="inputDisabled" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="submit" :disabled="submitDisabled">
                        确定
                    </el-button>
                    <el-button type="primary" @click="dialogVisible = false">取消</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 删除操作确认弹窗 -->
        <el-dialog title="提示" v-model="deleteDialogVisible" width="30%">
            <span>确定删除该种鸟类吗？</span>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="deleteUserInfo">确定</el-button>
                    <el-button type="primary" @click="deleteDialogVisible = false">取消</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<style scoped>
.container {
    display: flex-column;
    justify-content: center;
    /* align-items: center; */
    margin: 10px;
    padding: 10px;
}

.upload-img {
    margin-top: 10px;
}

.upload-sound {
    margin-top: 10px;
}

/* .custom-textarea {
    max-height: 150px;
    overflow-y: auto; 
} */
</style>